package mspbots.liongard.client.core.app;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.liongard.client.core.AbstractToolsUtil;
import mspbots.liongard.client.core.BaseSyncService;
import mspbots.liongard.client.core.client.ClientProperties;
import mspbots.liongard.common.QueryParams;
import mspbots.liongard.common.RedisKeys;
import mspbots.liongard.common.ResultSync;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.Map;

/**
 * TeamsService
 *
 * @author <a href="https://github.com/vnobo">Alex bob</a>
 * @date Created by 2020/8/28
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class AppServiceImpl extends AbstractToolsUtil {

    private final Map<String, BaseSyncService> syncServiceMap;
    private final ReactiveStringRedisTemplate stringRedisTemplate;

    public Mono<Boolean> onOff(Long tenantId, String onOff) {
        if ("ON".equals(onOff.toUpperCase())) {
            return this.stringRedisTemplate.opsForValue()
                    .set(RedisKeys.ON_OFF_TENANT_TASK_REDIS_KEY + ":" + tenantId, onOff.toUpperCase(),
                            Duration.ofDays(365));
        } else {
            return this.stringRedisTemplate.opsForValue()
                    .delete(RedisKeys.ON_OFF_TENANT_TASK_REDIS_KEY + ":" + tenantId);
        }
    }

    public Mono<Boolean> initialize(ClientProperties properties) {
        return this.liongardClient.count("/environments/count/", QueryParams.withDefault())
                .subscriberContext(ctx -> ctx.put("properties", properties))
                .map(resNode -> resNode > 0)
                .flatMap(res -> super.reactiveRedisTemplate.opsForValue()
                        .set(RedisKeys.TENANT_PROPERTIES_REDIS_KEY_PREFIX + properties.getTenantId(),
                                properties, Duration.ofDays(36500)))
                .doOnNext(res -> Flux.fromStream(this.syncServiceMap.values().parallelStream())
                        .flatMap(v -> Flux.concatDelayError(v.syncFast(properties), v.syncSlow(properties)))
                        .subscribe());
    }

    public Mono<Object> synchronise(Long tenantId, SyncRequest syncRequest) {
        return Mono.empty();
    }
}
